#include <2025Linux.h>
int main(int argc, char *argv[])
{
    // ./00_select_azhen 1.pipe 2.pipe
    ARGS_CHECK(argc,3);
    int fdw = open(argv[1],O_WRONLY);
    int fdr = open(argv[2],O_RDONLY);
    printf("azhen is connected!\n");
    char buf[4096];
    ssize_t ret;
    fd_set rdset; //rdset是监听集合
    //如果aqiang很长一段时间没说话，就退出
    time_t lastActive = time(NULL); //lastActive记录阿强上次说话的时间 
    time_t now = time(NULL);
    printf("now = %s\n", ctime(&now));
    while(1){
        FD_ZERO(&rdset);
        FD_SET(STDIN_FILENO,&rdset);
        FD_SET(fdr,&rdset);
        struct timeval timeout; //有一个固定的超时时间是1秒
        timeout.tv_sec = 1;
        timeout.tv_usec = 0;
        select(fdr+1,&rdset,NULL,NULL,&timeout); 
        now = time(NULL);//无论是阿珍说活、还是阿强说活、还是超时，都更新一下now
        printf("now = %s\n", ctime(&now));//打印一下当前时间
        if(FD_ISSET(STDIN_FILENO,&rdset)){//
            memset(buf,0,sizeof(buf));
            ret = read(STDIN_FILENO,buf,sizeof(buf));
            if(ret == 0){
                write(fdw,"nishigehaoren",13);
                break;
            }
            write(fdw,buf,strlen(buf));
        }
        if(FD_ISSET(fdr,&rdset)){
            lastActive = now;//如果是阿强说话，还要更新一下阿强的活跃时间
            memset(buf,0,sizeof(buf));
            ret = read(fdr,buf,sizeof(buf));
            if(ret == 0){
                printf("Hehe!\n");
                break;
            }
            printf("buf = %s\n", buf);
        }
        if(now - lastActive >= 10){//在所有时间都更新完成以后，判断一下是否超时
            printf("aqiang is quit!\n");
            break;
        }
    }
    close(fdw);
    close(fdr);
    return 0;
}

